package com.jxc.summer.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gry.work.util.interceptor.SessionInterceptor;
import com.jxc.summer.domain.Account;
import com.jxc.summer.service.LoginService;
import com.jxc.summer.util.MD5Util;
import com.jxc.summer.util.ReturnT;

/**
 * @author 耿瑞阳
 *
 */
@Controller
public class LoginController {

	public static String CURRENT_ACCOUNT_COMPANY_CODE = "accountCompanyCode";
	
	@Autowired
	private LoginService loginService;
	
	@RequestMapping("/")
	public String index(Model model, HttpServletRequest request) {
		if(request.getSession().getAttribute(SessionInterceptor.SEESION_CURRNETACCOUNT)!=null){
			return "index";
		}
		return "login";
	}
	
	@ResponseBody
	@RequestMapping("/login")
	public ReturnT<String> login(@RequestParam(value="userName") String username,@RequestParam(value="password") String password, HttpServletRequest request,HttpSession session) throws Exception {
		password = MD5Util.MD5(password);
		Account account = loginService.login(username, password);
		if(account == null){
			return new ReturnT<String>(500, "账号或密码错误");
		}else{
			session.setAttribute(SessionInterceptor.SEESION_CURRNETACCOUNT, account);
			//获取账户的权限、菜单信息存在session中。
			//更新账户信息，登陆时间，ip，次数
			String accessIp = getRemoteHost(request);
			account.setAccLastLoginIp(accessIp);
			loginService.updateAccount(account);
			//获取账户所属公司code
			Map<String,Object> params = new HashMap<String, Object>();
			params.put("accountId", account.getAccId());
			session.setAttribute(CURRENT_ACCOUNT_COMPANY_CODE, loginService.getAccountCompanyCode(params));
			return ReturnT.SUCCESS;
		}
	}
	@ResponseBody
	@RequestMapping("/logout")
	public ReturnT<String> logout(HttpSession session) throws Exception {
		session.removeAttribute(SessionInterceptor.SEESION_CURRNETACCOUNT);
		return ReturnT.SUCCESS;
	}
	
	public String getRemoteHost(javax.servlet.http.HttpServletRequest request){
	    String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;
	}
	
}
